package utl.mofen.script;

import java.util.Hashtable;
import java.util.Iterator;

import java.util.Map.Entry;
import java.util.regex.Pattern;


import com.google.gson.JsonElement;


public class SQLParser {
	ScriptObjectCenter soc = null;
	String ver = "";
	int key;
	int step;
	Hashtable<String, String> params = new Hashtable<String, String>();
	
	public void checkInitialize(String dbid)
	{
		soc = ScriptObjectFactory.getSOC(dbid);
	}
	
	public void checkInitialize(ScriptObjectCenter __soc)
	{
		soc = __soc;
	}

	public SQLParser() {
	}

	public void setScriptKey(int scriptKey) {
		this.key = scriptKey;
	}

	public void setScriptStep(int scriptStep) {
		this.step = scriptStep;
	}
	
	private String getSysEndScript()
	{
		String s =
			   "\n" +
               "GOTO _OK_END\n" +
			   "_ERR_END:\n" +
			   "_OK_END:\n";
		return s;
	}

	public void setParam(String key, String value) {
		params.put(key.toLowerCase(), value);
	}

	public void setDefaultVer(String ver)
	{
		this.ver = ver;
	}
	
	public void clear()
	{
		params.clear();		
	}
	

	public String getScript() throws Exception {
		if (soc==null)
		{
			throw new Exception("脚本对象中心尚未进行初始化!");
		}
		ScriptObject sObj = soc.getScriptObject(String.valueOf(key), this.ver);
		String sql = sObj.getSectionScript(step);

		
		//System.out.println("处理替换参数");
		//{"$rep_type":{"oName":"$rep_type"},"$rep_where":{"oName":"$rep_Where"}}
		//进行替换		
		Iterator<Entry<String, JsonElement>> repl_it = sObj.getRepl().entrySet().iterator();
		
		if (repl_it != null) {
			while(repl_it.hasNext())
			{
				Entry<String, JsonElement> e = repl_it.next();
				//System.out.print(e.getKey()+ "-----");
				//System.out.print(e.getValue().toString()+"\n");	
				String p = e.getValue().getAsJsonObject().get("oName").getAsString();
				//System.out.println(p);			
				//System.out.println("参数中的值:" + this.params.get(p));
				
				String pv = this.params.get(p.toLowerCase());
				if (pv==null) pv="";			
				
				sql = sql.replaceAll("(?i)"+Pattern.quote(p), pv);				
				
			}
		}
		
		
		//System.out.println("处理设置参数");
		//{"@mm_Key":{"type":"uniqueidentifier","kind":""},}
		Iterator<Entry<String, JsonElement>> param_it = sObj.getParam().entrySet().iterator();
		StringBuilder sb_param = new StringBuilder();
		StringBuilder sb_paramValue = new StringBuilder();
		String param_sql = "";
		if (param_it != null && param_it.hasNext()) {
			
			sb_param.append("DECLARE");			
		
			while(param_it.hasNext())
			{
				Entry<String, JsonElement> e = param_it.next();
				String p_name = e.getKey();
				String p_type = e.getValue().getAsJsonObject().get("type").getAsString(); 
				
				sb_param.append("\n   " + p_name + " " + p_type + ",");

				String pv = this.params.get(p_name.toLowerCase());
				if (pv==null)
				{
					sb_paramValue.append("SET " + p_name + "=NULL\n");
				}else
				{
					if (p_type.startsWith("numeric")							
							||p_type.startsWith("int")
							||p_type.startsWith("bit")
							||p_type.startsWith("decimal")
						)
					{						
					    sb_paramValue.append("SET " + p_name + "=" + pv.toString() + "\n");
					}else
					{
						sb_paramValue.append("SET " + p_name + "='" + pv.toString() + "'\n");
					}
				}
			}
			//删除最后一个","
			if (sb_param.length() > 1)
			{
			   sb_param.delete(sb_param.length()-1 , sb_param.length());
			}
			param_sql = sb_param.toString() + "\n\n" +
				    sb_paramValue.toString() + "\n";
		}		
		

		return String.format("/*script key=%d, step=%d*/\n", this.key, this.step) + 
				param_sql +
				sql.trim() + "\n\n" +
				getSysEndScript();
				
	}
}
